package com.rentong.wx.cust.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.rentong.basic.BusinessException;
import com.rentong.common.RedisUtils;
import com.rentong.common.TokenUtils;
import com.rentong.constants.RedisKeyEnum;
import com.rentong.wx.cust.dao.*;
import com.rentong.wx.cust.domain.*;
import com.rentong.wx.cust.dto.*;
import com.rentong.wx.cust.service.WxCustUserService;
import com.rentong.wx.sys.dao.SysConfShopTypeDao;
import com.rentong.wx.sys.domain.SysConfShopTypeEntity;
import com.rentong.wx.utils.HttpRequest;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.util.*;
import java.util.concurrent.TimeUnit;

/**
 * @Author: zhangle
 * @Description:
 * @Date: 2018/5/14 13:22
 */
@Service
public class WxCustUserServiceImpl implements WxCustUserService {
    @Resource
    private WxCustUserMapper wxCustUserMapper;

    @Resource
    private WxWxUserInfoMapper wxWxUserInfoMapper;

    @Resource
    private RedisUtils redisUtils;

    @Resource
    private SysConfShopTypeDao sysConfShopTypeDao;

    @Resource
    private CustUserCaixiDao custUserCaixiDao;

    @Resource
    private CustUserServiceDao custUserServiceDao;

    @Resource
    private CustGuanzhuDao custGuanzhuDao;

    @Resource
    private CustServiceOrderDao custServiceOrderDao;

    @Resource
    private CustServiceOrderPingjiaDao custServiceOrderPingjiaDao;

    @Resource
    private CustUserServiceTimeDao custUserServiceTimeDao;

    @Resource
    private CustUserChefPicDao custUserChefPicDao;

    private Long timeout = 10000 * 60 * 60L;


    @Transactional(rollbackFor = Exception.class)
    @Override
    public WxCustUserDto getChefServiceIntroduce(WxCustUser wxCustUser) {
        WxCustUserDto wcu = wxCustUserMapper.getUserInfo(wxCustUser);

        //擅长菜系
        String strCaixi = "";
        List<CustUserCaixiEntityDto> list = custUserCaixiDao.getCaixiByCustId(wxCustUser.getCustId());
        for (int i = 0; i < list.size(); i++) {
            strCaixi += list.get(i).getCaixiId() + ",";
        }
        if (!"".equals(strCaixi) && strCaixi.length() > 0) {
            strCaixi = strCaixi.substring(0, strCaixi.length() - 1);
        }
        wcu.setCaixiIds(strCaixi);


        //菜品图片
        List<CustUserChefPicEntity> chefPicList = custUserChefPicDao.getChefPicByCustId(wxCustUser.getCustId());
        wcu.setChefPicList(chefPicList);


        //擅长服务
        List<CustUserServiceEntityDto> userServiceList = custUserServiceDao.getServiceByCustId(wxCustUser.getCustId());
        wcu.setUserServiceList(userServiceList);

        return wcu;
    }


    @Transactional(rollbackFor = Exception.class)
    @Override
    public void updateUserPicByCustId(WxCustUser wxCustUser) {
        wxCustUser.setUpdateTime(new Date());
        wxCustUser.setZhengshuTime(new Date());
        wxCustUser.setZhengshuStat(1);
        wxCustUserMapper.updateByPrimaryKeySelective(wxCustUser);
    }


    @Transactional(rollbackFor = Exception.class)
    @Override
    public WxCustUserDto getChefDetailChefInfo(WxCustUserDto wxCustUserDto) {
        WxCustUserDto wcud = wxCustUserMapper.getChefDetailChefInfo(wxCustUserDto);


        //菜品图片，用于轮播图
        List<CustUserChefPicEntity> chefPicList = custUserChefPicDao.getChefPicByCustId(wxCustUserDto.getCustId());
        wcud.setChefPicList(chefPicList);


        //查询出用户的意向店铺、菜系、服务
        List<SysConfShopTypeEntity> shopTypeList = sysConfShopTypeDao.getShopTypeByIds(wcud.getShopTypeIds());
        List<CustUserCaixiEntityDto> caixiList = custUserCaixiDao.getCaixiByCustId(wcud.getCustId());
        List<CustUserServiceEntityDto> serviceList = custUserServiceDao.getServiceByCustId(wcud.getCustId());

        List<CustUserServiceEntity> shangwuyanqingList = new ArrayList<>();
        List<CustUserServiceEntity> daibanList = new ArrayList<>();

        for (int j = 0; j < serviceList.size(); j++) {
            if (serviceList.get(j).getBigTypeId() == 1L) {
                //代班服务（到店代厨）
                daibanList.add(serviceList.get(j));

            } else {
                //商务宴请（到家私厨）
                shangwuyanqingList.add(serviceList.get(j));

            }
        }

        //给意向店铺、菜系、商务宴请、代班服务赋值
        //传给前端（每种类型，所有数量都传给了前端，文档里写下，让前端控制每样展示几个）
        wcud.setShopTypeList(shopTypeList);
        wcud.setCaixiList(caixiList);
        wcud.setShangwuyanqingList(shangwuyanqingList);
        wcud.setDaibanList(daibanList);

        //查询下关注与未关注
        BigDecimal num = custGuanzhuDao.getCustGuanzhuByCustId(wxCustUserDto.getCId(), wxCustUserDto.getCustId());
        wcud.setGuanzhu(num);


        //可预约日
        List<CustUserServiceTimeEntity> csotList = custUserServiceTimeDao.getServiceTimeByCustId(wxCustUserDto.getCId());
        if (csotList != null && csotList.size() > 0) {
            String str = "";
            for (int i = 0; i < csotList.size(); i++) {
                if (csotList.get(i).getZhouji() == 1) {
                    str = str + "周一、";
                } else if (csotList.get(i).getZhouji() == 2) {
                    str = str + "周二、";
                } else if (csotList.get(i).getZhouji() == 3) {
                    str = str + "周三、";
                } else if (csotList.get(i).getZhouji() == 4) {
                    str = str + "周四、";
                } else if (csotList.get(i).getZhouji() == 5) {
                    str = str + "周五、";
                } else if (csotList.get(i).getZhouji() == 6) {
                    str = str + "周六、";
                } else if (csotList.get(i).getZhouji() == 7) {
                    str = str + "周日、";
                }
            }
            wcud.setCanBookingDay(str.substring(0, str.length() - 1));
        } else {
            wcud.setCanBookingDay("已约满");
        }


        //可约时间
        if (csotList != null && csotList.size() > 0) {
            String str = "";
            for (int i = 0; i < csotList.size(); i++) {
                str = str + ",";
                if (csotList.get(i).getMorningFabu() == 1) {
                    str = str + "1";
                } else if (csotList.get(i).getAfternoonFabu() == 1) {
                    str = str + "2";
                } else if (csotList.get(i).getNightFabu() == 1) {
                    str = str + "3";
                }
            }

            if (str.contains("123")) {
                wcud.setCanBookingTime("全天");
            } else if (str.contains("1")) {
                wcud.setCanBookingTime("上午");
            } else if (str.contains("2")) {
                wcud.setCanBookingTime("下午");
            } else if (str.contains("3")) {
                wcud.setCanBookingTime("夜宵");
            } else {
                wcud.setCanBookingTime("已约满");
            }

        } else {
            wcud.setCanBookingTime("已约满");
        }

        return wcud;
    }


    @Transactional(rollbackFor = Exception.class)
    @Override
    public List<CustServiceOrderPingjiaEntityDto> getChefDetailServicePingjia(WxCustUserDto wxCustUserDto) {
        return custServiceOrderPingjiaDao.getPingjiaByChefId(wxCustUserDto);
    }


    @Transactional(rollbackFor = Exception.class)
    @Override
    public void updateBizInfo(WxCustUser wxCustUser) {
        wxCustUser.setBizType(3);
        wxCustUser.setUpdateTime(new Date());
        wxCustUserMapper.updateByPrimaryKeySelective(wxCustUser);
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public WxCustUserDto getUserInfo(WxCustUser wxCustUser) {
        WxCustUserDto wcu = wxCustUserMapper.getUserInfo(wxCustUser);

        //好评率
        if ("0".equals(wcu.getPingjiaNum().toString())) {
            wcu.setPingjia("0%");
        } else {
            wcu.setPingjia((wcu.getHaopingNum() * 100 / wcu.getPingjiaNum()) + "%");
        }

        //关注
        BigDecimal guanzhu = custGuanzhuDao.getGuanzhuNum(wxCustUser.getCustId());
        wcu.setGuanzhu(guanzhu);

        //粉丝
        BigDecimal fensi = custGuanzhuDao.getFensiNum(wxCustUser.getCustId());
        wcu.setFensi(fensi);

        //我的订单中的小角标（用户身份，超过99个就显示99+）：orderNumListUser
        List<CustServiceOrderEntityDto> userList = custServiceOrderDao.getOrderNumListUser(wxCustUser.getCustId());
        List<Integer> orderNumListUser = new ArrayList<>();
        orderNumListUser.add(0);
        orderNumListUser.add(0);
        orderNumListUser.add(0);
        orderNumListUser.add(0);
        orderNumListUser.add(0);
        orderNumListUser.add(0);

        //集合不为空，表示用户有对应状态的订单
        if (userList != null && userList.size() > 0) {
            for (int i = 0; i < userList.size(); i++) {
                if (userList.get(i).getOrderState() == 1) {
                    //待预约
                    orderNumListUser.set(0, userList.get(i).getNum());

                } else if (userList.get(i).getOrderState() == 2) {
                    //待接单
                    orderNumListUser.set(1, userList.get(i).getNum());

                } else if (userList.get(i).getOrderState() == 3) {
                    //待服务
                    orderNumListUser.set(2, userList.get(i).getNum());

                } else if (userList.get(i).getOrderState() == 4) {
                    //服务中
                    orderNumListUser.set(3, userList.get(i).getNum());

                } else if (userList.get(i).getOrderState() == 5) {
                    //待确认
                    orderNumListUser.set(4, userList.get(i).getNum());

                } else if (userList.get(i).getOrderState() == 8) {
                    //售后中
                    orderNumListUser.set(5, userList.get(i).getNum());

                }
            }
        }
        wcu.setOrderNumListUser(orderNumListUser);


        //我的订单中的小角标（厨师身份，超过99个就显示99+）：orderNumListChef
        List<CustServiceOrderEntityDto> chefList = custServiceOrderDao.getOrderNumListChef(wxCustUser.getCustId());
        List<Integer> orderNumListChef = new ArrayList<>();
        orderNumListChef.add(0);
        orderNumListChef.add(0);
        orderNumListChef.add(0);
        orderNumListChef.add(0);
        orderNumListChef.add(0);
        orderNumListChef.add(0);

        //集合不为空，表示用户有对应状态的订单
        if (chefList != null && chefList.size() > 0) {
            for (int i = 0; i < chefList.size(); i++) {
                if (chefList.get(i).getOrderState() == 1) {
                    //待预约
                    orderNumListChef.set(0, chefList.get(i).getNum());

                } else if (chefList.get(i).getOrderState() == 2) {
                    //待接单
                    orderNumListChef.set(1, chefList.get(i).getNum());

                } else if (chefList.get(i).getOrderState() == 3) {
                    //待服务
                    orderNumListChef.set(2, chefList.get(i).getNum());

                } else if (chefList.get(i).getOrderState() == 4) {
                    //服务中
                    orderNumListChef.set(3, chefList.get(i).getNum());

                } else if (chefList.get(i).getOrderState() == 5) {
                    //待确认
                    orderNumListChef.set(4, chefList.get(i).getNum());

                } else if (chefList.get(i).getOrderState() == 8) {
                    //售后中
                    orderNumListChef.set(5, chefList.get(i).getNum());

                }
            }
        }
        wcu.setOrderNumListChef(orderNumListChef);


        return wcu;
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public Integer updateInformation(AddInsertInformationDto addInsertInformationDto) {
        return wxCustUserMapper.updateInformation(addInsertInformationDto);
    }


    @Transactional(rollbackFor = Exception.class)
    @Override
    public List<WxCustUserDto> getChefList(WxCustUserDto wxCustUserDto) {
        //查询出可展示的厨师列表
        List<WxCustUserDto> wcudList = wxCustUserMapper.getChefList(wxCustUserDto);

        //修改部分数据
        for (int i = 0; i < wcudList.size(); i++) {
            WxCustUserDto wcud = wcudList.get(i);

            //查询出用户的意向店铺、菜系、服务
            List<SysConfShopTypeEntity> shopTypeList = sysConfShopTypeDao.getShopTypeByIds(wcud.getShopTypeIds());
            List<CustUserCaixiEntityDto> caixiList = custUserCaixiDao.getCaixiByCustId(wcud.getCustId());
            List<CustUserServiceEntityDto> serviceList = custUserServiceDao.getServiceByCustId(wcud.getCustId());

            List<CustUserServiceEntity> shangwuyanqingList = new ArrayList<>();
            List<CustUserServiceEntity> daibanList = new ArrayList<>();

            for (int j = 0; j < serviceList.size(); j++) {
                if (serviceList.get(j).getBigTypeId() == 1L) {
                    //代班服务（到店代厨）
                    daibanList.add(serviceList.get(j));

                } else {
                    //商务宴请（到家私厨）
                    shangwuyanqingList.add(serviceList.get(j));

                }
            }

            //给意向店铺、菜系、商务宴请、代班服务赋值
            //传给前端（每种类型，所有数量都传给了前端，文档里写下，让前端控制每样展示几个）
            wcudList.get(i).setShopTypeList(shopTypeList);
            wcudList.get(i).setCaixiList(caixiList);
            wcudList.get(i).setShangwuyanqingList(shangwuyanqingList);
            wcudList.get(i).setDaibanList(daibanList);

        }

        return wcudList;
    }


    @Transactional(rollbackFor = Exception.class)
    @Override
    public WxUserInfo registerByPhone(String code, String phone, String phoneCode) throws Exception {
        //判断下验证码是否正确
        String codes = redisUtils.get(RedisKeyEnum.redis_SMS.getKey() + phone);
        if (phoneCode.equals(codes)) {
            //删除验证码
            redisUtils.delete(RedisKeyEnum.redis_SMS.getKey() + phone);
        } else {
//            throw new BusinessException("验证码不正确！");
            return null;
        }

        Map map = new HashMap();
        //小程序唯一标识   (在微信小程序管理后台获取)
        String wxspAppid = "wx25277e38d6aa9020";
        //小程序的 app secret (在微信小程序管理后台获取)
        String wxspSecret = "e5333df4bf7814046d67073a7173307e";
        //授权（必填）
        String grant_type = "authorization_code";
        //////////////// 1、向微信服务器 使用登录凭证 code 获取 session_key 和 openid
        //请求参数
        String params = "appid=" + wxspAppid + "&secret=" + wxspSecret + "&js_code=" + code + "&grant_type=" + grant_type;
        //发送请求
        String sr = HttpRequest.sendGet("https://api.weixin.qq.com/sns/jscode2session", params);
        //解析相应内容（转换成json对象）
        JSONObject json = JSONObject.parseObject(sr);
        //用户的唯一标识（openid）
        String openid = (String) json.get("openid");
        //////////////// 2、对encryptedData加密数据进行AES解密 ////////////////
        try {
            //判断用户是否已经注册
            WxUserInfo wxUserInfo = wxWxUserInfoMapper.getUserByPhone(phone);
            if (wxUserInfo != null) {
                //已经注册，更新下openId
                WxCustUser wcu = new WxCustUser();
                wcu.setCustId(wxUserInfo.getCustId());
                wcu.setOpenId(openid);
                wxCustUserMapper.updateByPrimaryKeySelective(wcu);

                //刷新token
                wxUserInfo = buildUserInfos(wxUserInfo);
                return wxUserInfo;
            }

            //用户信息入库
            WxUserInfo wxUser = new WxUserInfo();
            wxUser.setPhone(phone);
            wxUser.setOpenId(openid);
            wxUser.setNickName("用户" + phone.substring(phone.length() - 4));
            //昵称修改
            wxWxUserInfoMapper.insertUserOpenId(wxUser);
            wxUserInfo = buildUserInfos(wxUser);

            return wxUserInfo;

        } catch (Exception e) {
            e.printStackTrace();
        }
        map.put("status", 0);
        map.put("msg", "解密失败");

        return null;
    }
//    @Transactional(rollbackFor = Exception.class)
//    @Override
//    public WxUserInfo registerByPhone(String code, String encryptedData, String iv) throws Exception {
//
//        Map map = new HashMap();
//        //小程序唯一标识   (在微信小程序管理后台获取)
//        String wxspAppid = "wxb29ce581f34c57dc";
//        //小程序的 app secret (在微信小程序管理后台获取)
//        String wxspSecret = "ef1e5883221a14521654f32c005f173d";
//        //授权（必填）
//        String grant_type = "authorization_code";
//        //////////////// 1、向微信服务器 使用登录凭证 code 获取 session_key 和 openid
//        //请求参数
//        String params = "appid=" + wxspAppid + "&secret=" + wxspSecret + "&js_code=" + code + "&grant_type=" + grant_type;
//        //发送请求
//        String sr = HttpRequest.sendGet("https://api.weixin.qq.com/sns/jscode2session", params);
//        //解析相应内容（转换成json对象）
//        JSONObject json = JSONObject.parseObject(sr);
//        //获取会话密钥（session_key）
//        String session_key = json.get("session_key").toString();
//        //用户的唯一标识（openid）
//        String openid = (String) json.get("openid");
//        String phoneNumber = "";
//        //////////////// 2、对encryptedData加密数据进行AES解密 ////////////////
//        try {
//            String result = AesUtil.decrypt(encryptedData, session_key, iv, "UTF-8");
//            if (null != result && result.length() > 0) {
//                map.put("status", 1);
//                map.put("msg", "解密成功");
//                JSONObject userInfoJSON = JSONObject.parseObject(result);
//                phoneNumber = userInfoJSON.get("phoneNumber").toString();
//            }
//            //判断用户是否已经注册
//            WxUserInfo wxUserInfo = wxWxUserInfoMapper.getUserByPhone(phoneNumber);
//            if (wxUserInfo != null) {
//                wxUserInfo = buildUserInfos(wxUserInfo);
//                return wxUserInfo;
//            }
//
//            //用户信息入库
//            WxUserInfo wxUser = new WxUserInfo();
//            wxUser.setPhone(phoneNumber);
//            wxUser.setOpenId(openid);
//            wxUser.setNickName("用户" + phoneNumber.substring(phoneNumber.length() - 4));
//            //昵称修改
//            wxWxUserInfoMapper.insertUserOpenId(wxUser);
//            wxUserInfo = buildUserInfos(wxUser);
//
//            return wxUserInfo;
//
//        } catch (Exception e) {
//            e.printStackTrace();
//        }
//        map.put("status", 0);
//        map.put("msg", "解密失败");
//
//        return null;
//    }

    @Override
    public WxUserInfo getCustInfo(String oldToken) throws Exception {
        //用户上一次的token
        String tokenKey = RedisKeyEnum.open_user_info.getKey() + oldToken;
        WxUserInfo aui = redisUtils.get(tokenKey, WxUserInfo.class);
        if (aui == null) {
            throw new BusinessException("110", "未登录");
        }
        return aui;
    }

    //光速洗车小程序注册后刷新token
    private WxUserInfo buildUserInfos(WxUserInfo wxUser) {
        Long wxUserId = wxUser.getCustId();
        //缓存用户信息
        String userKey = RedisKeyEnum.open_login_key.getKey() + wxUserId;
        //用户上一次的token
        String oldToken = redisUtils.get(userKey, String.class);
        String tokenKey;
        //已经缓存过的，删除
        if (StringUtils.isNotBlank(oldToken)) {
            tokenKey = RedisKeyEnum.open_user_info.getKey() + oldToken;
            redisUtils.delete(tokenKey);
        }
        //当缓存新的token
        String newToken = TokenUtils.getToken(wxUserId.toString());

        WxUserInfo wxUserInfo = new WxUserInfo();
        BeanUtils.copyProperties(wxUser, wxUserInfo);
        wxUserInfo.setToken(newToken);
//        wxUserInfo.setSessionKey(sessionKey);
        wxUserInfo.setCustId(wxUserId);

        tokenKey = RedisKeyEnum.open_user_info.getKey() + newToken;
        //缓存key
        redisUtils.set(userKey, newToken, timeout, TimeUnit.SECONDS);
        //缓存用户信息
        redisUtils.set(tokenKey, wxUserInfo, timeout, TimeUnit.SECONDS);

        return wxUserInfo;
    }


}
